<template>
    <div style="height: 100%;">
      <a-radio-group type="button" v-model="orderOrRefund" style="margin-bottom: 10px;" @change="onChange">
      <a-radio :value="1">订单</a-radio>
      <a-radio :value="0">退单</a-radio>
    </a-radio-group>

      <a-table stripe :columns="columnsTable" :data="responseResult.columnsTableList" :expandable="expandableColumnsTable" row-key="sn" v-if="responseResult.columnsTableList.length && orderOrRefund === 1"
               :pagination="paginationParams" @page-change="pageChange">
        <template #orderStatus="{record}"><div>{{orderClientStatus[record.orderStatus]}}</div></template>
        <template #flowPrice="{record}"><div>{{unitPrice(record.flowPrice, '￥')}}</div></template>
        <template #options="{ record }"><a-button type="text" @click="orderDetails(record)">查看</a-button></template>
      </a-table>
      <a-table stripe :columns="refundColumns" :data="responseResult.refundColumnsList" :expandable="expandableRefundColumns" row-key="sn" v-if="responseResult.refundColumnsList.length && orderOrRefund === 0"
               :pagination="paginationParams" @page-change="pageChange">
        <template #goodsImage="{ record }"><a-image width="60" :src="record.goodsImage"></a-image></template>
        <template #serviceType="{ record }"><div>{{serviceTypeClient[record.serviceType]}}</div></template>
        <template #serviceStatus="{ record }"><div>{{serviceStatusClient[record.serviceStatus]}}</div></template>
        <template #applyRefundPrice="{ record }"><div>{{unitPrice(record.applyRefundPrice, '￥')}}</div></template>
        <template #flowPrice="{ record }"><div>{{unitPrice(record.flowPrice, '￥')}}</div></template>
        <template #options="{ record }"><a-button type="text" @click="refundDetails(record)">查看</a-button></template>
      </a-table>
    </div>
  </template>
  
  <script lang="ts" setup>
    import { onMounted, reactive, watch, ref, h} from 'vue';
    import { statisticsOrderList,statisticsOrderRefundList } from '@/api/statisitics';
    import { MethodsRule, ColumnsDataRule,PreViewParamsRule } from '@/types/global';
    import { orderStatus,afterSalesType,serviceStatus } from '@/utils/tools';
    import { useRouter } from 'vue-router';
    import { orderClientStatus, payStatusClient, paymentMethodClient, serviceTypeClient, serviceStatusClient, serviceTypeList } from '@/utils/typeEnumeration';
    import { unitPrice } from '@/utils/filters';

    const router = useRouter();
    const orderOrRefund = ref(1); // 订单or退单
    const props = defineProps({
      dateType: {
        type: Object,
        default: () => {
          return {
            recent: 'LAST_SEVEN',
            month: '',
          };
        },
      },
    });

    // 订单请求参数
    const previewParams = reactive<PreViewParamsRule>({
      searchType: props.dateType.recent, // TODAY ,  YESTERDAY , LAST_SEVEN , LAST_THIRTY
    });

    interface ResponseRule {
      columnsTableList: Array<any>,
      refundColumnsList: Array<any>
    }
    const responseResult = reactive<ResponseRule>({
      columnsTableList: [],
      refundColumnsList: []
    });
    // 分页的属性配置
    const paginationParams = ref();
    // 订单统计
    const columnsTable = [
      {title: '商家名称', dataIndex: 'storeName'},
      {title: '用户名', dataIndex: 'memberName'},
      {title: '订单状态', dataIndex: 'orderStatus', slotName:'orderStatus'},
      {title: '创建时间', dataIndex: 'createTime'},
      {title: '支付时间', dataIndex: 'paymentTime'},
      {title: '价格', dataIndex: 'flowPrice', slotName:'flowPrice'},
      {title: '操作', slotName: 'options'}
    ];
    // 退单统计
    const refundColumns = [
      {title: '商品图片', dataIndex: 'goodsImage', slotName: 'goodsImage'},
      {title: '商品名称', dataIndex: 'goodsName'},
      {title: '商家名称', dataIndex: 'storeName'},
      {title: '售后单类型', dataIndex: 'serviceType', slotName: 'serviceType'},
      {title: '售后单状态', dataIndex: 'serviceStatus', slotName: 'serviceStatus'},
      {title: '退款时间', dataIndex: 'refundTime'},
      {title: '申请退款金额', dataIndex: 'applyRefundPrice', slotName: 'applyRefundPrice'},
      {title: '申请原因', dataIndex: 'reason'},
      {title: '实际金额', dataIndex: 'flowPrice', slotName: 'flowPrice'},
      {title: '操作', slotName: 'options'}
    ];
    // 订单的展开行配置
    const expandableColumnsTable = reactive({
      title: '',
      width: 80,
      slotName: 'extra',
      expandedRowRender:(record: any)=>{
        return h('div',{
              style: {color: "", border: ""},
              class: "my-expandable",
              id: "",
            }, [
              // "render函数文本" 文本内容可以直接写入
              h("div", [
                h('div',{class: "title"}, '订单详情'),
                h('div',{class: "order-detail"}, [
                  h('p', [h('span', '订单来源'),h('span', record.clientType)]),
                  h('p', [h('span', '订单状态'),h('span', orderClientStatus[record.orderStatus])]),
                  h('p', [h('span', '付款状态'),h('span', payStatusClient[record.payStatus])]),
                  h('p', [h('span', '支付时间'),h('span', record.paymentTime)]),
                  h('p', [h('span', '支付方式'),h('span', paymentMethodClient[record.paymentMethod])]),
                  h('p', [h('span', '用户名'),h('span', record.memberName)]),
                  h('p', [h('span', '店铺名称'),h('span', record.storeName)]),
                  h('p', [h('span', '创建时间'),h('span', record.createTime)]),
                ]),
                h('div',{class: "title"}, '商品详情'),
                record.orderItems.map((item: any) => {return h('div',{class: 'goods-detail'},
                    [h('img', {src:item.image}),h('div', [h('p', item.name),h('p', `x${item.num}`),h('p', unitPrice(item.goodsPrice, '￥'))])]
                )}),
                h('div', {class: "flow-price"}, [h('span', '总价格'),h('span', unitPrice(record.flowPrice, '￥'))])
              ]), // h()创建的VNodes
              // h({template: `<div><div>${record.orderItems[0].sn}</div></div>`})
            ]
        );
      }
    });
    // 退单的展开行配置
    const expandableRefundColumns = reactive({
      title: '',
      width: 80,
      slotName: 'extra',
      expandedRowRender:(record: any)=>{
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        return h('div',{
              style: {color: "", border: ""},
              class: "my-expandable",
              id: "",
            }, [
              // "render函数文本" 文本内容可以直接写入
              h("div", [
                h('div',{class: "title"}, '售后详情'),
                h('div',{class: "order-detail"}, [
                  h('p', [h('span', '售后类型'),h('span', serviceTypeList[record.serviceType])]),
                  h('p', [h('span', '售后单状态'),h('span', serviceStatusClient[record.serviceStatus])]),
                  h('p', [h('span', '退款时间'),h('span', record.refundTime)]),
                  h('p', [h('span', '申请退款金额'),h('span', unitPrice(record.applyRefundPrice, '￥'))]),
                  h('p', [h('span', '商家备注'),h('span', record.auditRemark)]),
                  h('p', [h('span', '申请原因'),h('span', record.reason)]),
                  h('p', [h('span', '用户名'),h('span', record.memberName)]),
                  h('p', [h('span', '店铺名称'),h('span', record.storeName)]),
                  h('p', [h('span', '创建时间'),h('span', record.createTime)]),
                ]),
                h('div',{class: "title"}, '商品详情'),
                h('div',{class: 'goods-detail'},
                    [h('img', {src:record.goodsImage}),h('div', [h('p', record.name),h('p', `x${record.num}`),h('p', unitPrice(record.goodsPrice, '￥'))])]
                ),
                h('div', {class: "flow-price"}, [h('span', '实际退款金额'),h('span', unitPrice(record.flowPrice, '￥'))])
              ]), // h()创建的VNodes
              // h({template: `<div><div>${record.orderItems[0].sn}</div></div>`})
            ]
        );
      }
    });
    // 订单跳转详情页
    const orderDetails = (record: any) => {
      router.push({
        name: 'order-detail',
        query: { id: record.sn },
      });
    };
    // 退单跳转详情页
    const refundDetails = (record: any) => {
      router.push({
        name: 'after-order-detail',
        query: { id: record.sn },
      });
    };
    // 统计相关--订单统计
    const getOrderList = async () => {
      const res = await statisticsOrderList(previewParams);
      if (res.data.success) {
        responseResult.columnsTableList = res.data.result.records;
        // responseResult.columnsTableList = res.data.result.records.map(item => {
        //   // 通过设置 expandable 开启展开行功能。可以在 data 中添加 expand 属性，设置展开行显示内容
        //   item.expand = JSON.stringify(item.orderItems);
        //   return item;
        // });
        paginationParams.value = res.data.result;
      }
    };
    // 统计相关--退单统计
    const getOrderRefundList = async () => {
      const res = await statisticsOrderRefundList(previewParams);
      if (res.data.success) {
        responseResult.refundColumnsList = res.data.result.records;
        paginationParams.value = res.data.result;
      }
    };
    // 表格分页
    const pageChange = (number: any) => {
      previewParams.pageNumber = number;
      if(orderOrRefund.value == 1){
        getOrderList()
      }else{
        getOrderRefundList();
      }
    };
    // 订单/退单切换
    const onChange = () => {
      if(orderOrRefund.value == 1){
        getOrderList()
      }else{
        getOrderRefundList();
      }
    };
    onMounted(() => {
      getOrderList();
      getOrderRefundList();
    });
    // 监听值的改变 父级值改变
    watch(
      () => props.dateType,
      (val) => {
        previewParams.searchType = val.recent;
        if (val.month) {
          // eslint-disable-next-line prefer-destructuring,no-nested-ternary
          previewParams.month = val.month.split('-')[1]
            ? val.month.split('-')[1].indexOf('0') != -1
              ? val.month.split('-')[1].substr(1)
              : ''
            : '';  
          // eslint-disable-next-line prefer-destructuring
          previewParams.year = val.month.split('-')[0];
        }
        getOrderList();
        getOrderRefundList();
      },
      {
        deep: true,
        immediate: true,
      }
    );
  </script>
  
  <style scoped lang="less">
    :deep(.my-expandable) {
      .title {
        font-size: 18px;
        line-height: 50px;
        font-weight: bold;
      }
      .order-detail {
        display: flex;
        flex-wrap: wrap;
        p {
          width: 300px;
          height: 40px;
          line-height: 40px;
          margin: 0;
          color: #666666;
          span:nth-of-type(1) {
            margin-right: 16px;
            font-weight: bold;
          }
        }
      }
      .goods-detail {
        display: flex;
        margin-bottom: 20px;
        img {
          width: 100px;
          height: 100px;
          border-radius: 10px;
        }
        > div {
          display: flex;
          flex-direction: column;
          justify-content: center;
          margin-left: 18px;
          p {
            margin: 0;
            line-height: 24px;
          }
          p:nth-of-type(3) {
            color: #FF0000;
            font-weight: bold;
          }
        }
      }
      .flow-price {
        text-align: right;
        padding-right: 20%;
        font-size: 16px;
        span:nth-of-type(1) {
          margin-right: 18px;
        }
        span:nth-of-type(2) {
          color: #FF0000;
          font-size: 24px;
          font-weight: bold;
        }
      }
    }
  </style>
  